//
//  BQHomePageViewController.m
//  Adorable_Things
//
//  Created by ybq on 16/1/11.
//  Copyright © 2016年 Banana Inc. All rights reserved.
//

#import "BQHomePageViewController.h"
#import "BQAdsView.h"
#import "BQCartoonView.h"
#import "BQAdsModel.h"
#import "BQCartoonModel.h"
#import "BQmengestView.h"
#import "BQMengestModel.h"
#import "BQTodayView.h"
#import "BQTodayModel.h"
#import "ZYCategorySecondCollectionViewCell.h"
#import "ZYCategorySecondPageModel.h"
#import "BQILView.h"
#import "BQNavBarView.h"
#import "ArticleDetailViewController.h"
#import "BQMissionCenterViewController.h"
#import "BQWelfare_BannerViewController.h"
#import "ATMainDetailViewController.h"
#import "BQHtmlViewController.h"
#import "DJSearchViewController.h"
#import "ZYCategorySearchViewController.h"


@interface BQHomePageViewController () <UIScrollViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, SDCycleScrollViewDelegate>

@property (nonatomic, strong) BQNavBarView *navBarView;
@property (nonatomic, strong) UIScrollView *mainScrollView;
@property (nonatomic, strong) NSMutableArray *cartoonDataArray;
@property (nonatomic, strong) NSMutableArray *mengestDataArray;
@property (nonatomic, strong) NSMutableArray *todayDataArray;
@property (nonatomic, strong) NSMutableArray *itemNewDataArray;
@property (nonatomic, strong) NSMutableArray *itemPopDataArray;
@property (nonatomic, strong) NSMutableArray *itemDataArray;
@property (nonatomic, strong) NSMutableArray *adsDataArray;
@property (nonatomic, strong) BQCartoonModel *cartoonModel;
@property (nonatomic, strong) BQAdsView *adsView;
@property (nonatomic, strong) SDCycleScrollView *adsCycleScrollView;
@property (nonatomic, strong) BQCartoonView *cartoonView;
@property (nonatomic, strong) BQmengestView *mengestView;
@property (nonatomic, strong) UIScrollView *todayScrollView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) UIView *titleView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) BQILView *newsItem;
@property (nonatomic, strong) BQILView *popItem;
@property (nonatomic, strong) BQILView *guessItem;
// 认证
@property (nonatomic, strong) UIButton *certificationButton;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) FMDatabase *db;   // FMDB里面的数据库,一个db就是一个数据库,每个数据库里可以放很多张表

@end

@implementation BQHomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    _adsDataArray = [NSMutableArray array];
    _cartoonDataArray = [NSMutableArray array];
    _mengestDataArray = [NSMutableArray array];
    _todayDataArray = [NSMutableArray array];
    _itemNewDataArray = [NSMutableArray array];
    _itemPopDataArray = [NSMutableArray array];
    // Do any additional setup after loading the view from its nib.
    [self requestData];
    [self createUI];
    [self createDataBase];
    _itemDataArray = _itemNewDataArray;
}

#pragma mark 布局
- (void)createUI {
    // 自定义导航条
    _navBarView = [[BQNavBarView alloc] initWithFrame:CGRectMake(0, 20, kWidth, 44)];
    _navBarView.backgroundColor = [UIColor whiteColor];
    ATUserManager *UserManager = [ATUserManager shareManager];
    if (UserManager.isLogin) {
        [_navBarView.avatarButton sd_setImageWithURL:[NSURL URLWithString:UserManager.avatar] forState:(UIControlStateNormal)];
    }
    _navBarView.avatarButton.adjustsImageWhenHighlighted = NO;
    [_navBarView.searchButton addTarget:self action:@selector(searchButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_navBarView];
    
    _mainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, kWidth, kHeight)];
    _mainScrollView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"LaunchImage-568h"]];
    _mainScrollView.showsVerticalScrollIndicator = NO;
    _mainScrollView.delegate = self;
    _mainScrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 0;
        [self requestData];
    }];
    _mainScrollView.scrollsToTop = YES;
    
    _adsView = [[BQAdsView alloc] init];
    _adsView.backgroundColor = [UIColor whiteColor];
    _adsView.frame = CGRectMake(0, 0, kWidth, _adsView.welfareButton.bottom + 15);
    
    __weak BQHomePageViewController *mySelf = self;
    mySelf.adsScroll = ^() {
        _adsCycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kWidth, kWidth / 2.27) delegate:self placeholderImage:[UIImage imageNamed:@"placeHolder-1"]];
        _adsCycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
        _adsCycleScrollView.currentPageDotColor = [UIColor redColor];
        _adsCycleScrollView.pageDotColor = [UIColor grayColor];
        NSMutableArray *imageURLGroup = [NSMutableArray array];
        for (BQAdsModel *model in _adsDataArray) {
            NSString *str = model.pic_url;
            [imageURLGroup addObject:str];
        }
        _adsCycleScrollView.imageURLStringsGroup = imageURLGroup;
        [_adsView addSubview:_adsCycleScrollView];
        
    };

    [_adsView.missionCenterButton addTarget:self action:@selector(missionCenterButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [_adsView.welfareButton addTarget:self action:@selector(welfareButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [_mainScrollView addSubview:_adsView];
    
    _cartoonView = [[BQCartoonView alloc] init];
    _cartoonView.backgroundColor = [UIColor whiteColor];
    _cartoonView.frame = CGRectMake(0, _adsView.bottom + 10, kWidth, _cartoonView.fifthButton.bottom + 15);
    [_mainScrollView addSubview:_cartoonView];
    
    _mengestView = [[BQmengestView alloc] initWithFrame:CGRectMake(0, _cartoonView.bottom + 10, kWidth, kWidth / 2.34)];
    _mengestView.scrollView.scrollsToTop = NO;
    _mengestView.backgroundColor = [UIColor whiteColor];
    [_mainScrollView addSubview:_mengestView];
    
    UILabel *cuteLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, _mengestView.bottom + 15, 50, 15)];
    cuteLabel.font = [UIFont systemFontOfSize:16];
    cuteLabel.text = @"萌物志";
    [_mainScrollView addSubview:cuteLabel];
/*
    UIButton *previousButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    previousButton.frame = CGRectMake(kWidth - 15 - 30, _mengestView.bottom + 18, 30, 12);
    previousButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [previousButton setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
    [previousButton setTitle:@"往期" forState:(UIControlStateNormal)];
    [previousButton addTarget:self action:@selector(previousButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [_mainScrollView addSubview:previousButton];
*/
    _todayScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, cuteLabel.bottom + 20, kWidth, kWidth / 1.31)];
    _todayScrollView.delegate = self;
    _todayScrollView.pagingEnabled = YES;
    _todayScrollView.scrollsToTop = NO;
    _todayScrollView.showsHorizontalScrollIndicator = NO;
    _todayScrollView.contentSize = CGSizeMake(kWidth * 10, kWidth / 1.31);
    for (int i = 0; i < 10; i++) {
        BQTodayView *todayView = [[BQTodayView alloc] initWithFrame:CGRectMake(15 + kWidth * i, 0, kWidth - 30, kWidth / 1.31)];
        todayView.layer.cornerRadius = 5;
        todayView.layer.masksToBounds = YES;
        todayView.backgroundColor = [UIColor whiteColor];
        todayView.tag = 200 + i;
        [_todayScrollView addSubview:todayView];
    }
    [_mainScrollView addSubview:_todayScrollView];
    
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake((kWidth - 160) / 2, _todayScrollView.bottom + 10, 160, 15)];
    _pageControl.numberOfPages = 10;
    _pageControl.pageIndicatorTintColor = [UIColor grayColor];
    _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    
    [_mainScrollView addSubview:_pageControl];
    
    _titleView = [[UIView alloc] initWithFrame:CGRectMake(0, _pageControl.bottom + 15, kWidth, 55)];
    _titleView.backgroundColor = [UIColor whiteColor];
    [_mainScrollView addSubview:_titleView];
    _newsItem = [[BQILView alloc] initWithFrame:CGRectMake(40, 15, 50, 20)];
    _newsItem.imageView.image = [UIImage imageNamed:@"iconfont-new-red"];
    _newsItem.label.text = @"上新";
    _newsItem.label.textColor = [UIColor redColor];
    _newsItem.userInteractionEnabled = YES;
    UITapGestureRecognizer *newTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_newsItem addGestureRecognizer:newTap];
    [_titleView addSubview:_newsItem];
    
    _popItem = [[BQILView alloc] initWithFrame:CGRectMake(_newsItem.right + (kWidth - 80 - 50 * 3) / 2, 15, 50, 20)];
    _popItem.imageView.image = [UIImage imageNamed:@"iconfont-iconkafei"];
    _popItem.label.text = @"人气";
    _popItem.label.textColor = [UIColor lightGrayColor];
    _popItem.userInteractionEnabled = YES;
    UITapGestureRecognizer *popTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_popItem addGestureRecognizer:popTap];
    [_titleView addSubview:_popItem];
    
    _guessItem = [[BQILView alloc] initWithFrame:CGRectMake(_popItem.right + (kWidth - 80 - 50 * 3) / 2, 15, 50, 20)];
    _guessItem.imageView.image = [UIImage imageNamed:@"iconfont-cloud"];
    _guessItem.label.text = @"猜你";
    _guessItem.label.textColor = [UIColor lightGrayColor];
    _guessItem.userInteractionEnabled = YES;
    UITapGestureRecognizer *guessTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_guessItem addGestureRecognizer:guessTap];
    [_titleView addSubview:_guessItem];
   
    _certificationButton = [[UIButton alloc] initWithFrame:CGRectMake(0, _titleView.bottom, kWidth, kWidth)];
    [_certificationButton setImage:[UIImage imageNamed:@"renzheng"] forState:(UIControlStateNormal)];
    _certificationButton.adjustsImageWhenHighlighted = NO;
    [_certificationButton addTarget:self action:@selector(certificationButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    _certificationButton.hidden = YES;
    [_mainScrollView addSubview:_certificationButton];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = 10;
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.itemSize = CGSizeMake((kWidth - 50) / 2, (kWidth - 50) / 2 + 85);
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 15, 15, 15);
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, _titleView.bottom, kWidth, kHeight - 49 - 55 - 64) collectionViewLayout:flowLayout];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page += 1;
        [self requestItemData];
    }];
    _collectionView.scrollsToTop = NO;
    [_collectionView registerNib:[UINib nibWithNibName:@"ZYCategorySecondCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ZYCategorySecondCollectionViewCell"];
    [_mainScrollView addSubview:_collectionView];
    
    _mainScrollView.contentSize = CGSizeMake(kWidth, _titleView.bottom + 64 + 49 + 50);
    [self.view addSubview:_mainScrollView];

}

#pragma mark -- FMDB
- (void)createDataBase {
    
    // 创建我们的数据库的路径,同时拼接数据库的名字
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"ATDataBase.db"];
    // 根据路径去创建一个数据库
    _db = [FMDatabase databaseWithPath:path];
    
    // 调用open方法打开数据库,成功返回YES,失败返回NO
    if ([_db open]) {
        NSLog(@"数据库打开成功");
    } else {
        NSLog(@"数据库打开失败");
    }
    // 调用db的executeUpdate,这个方法的参数就是sql语句
    [_db executeUpdate:@"CREATE TABLE AdsList (pic_url text)"];
    [_db executeUpdate:@"CREATE TABLE CartoonList (pic_url text)"];
    [_db executeUpdate:@"CREATE TABLE MengestList (pic_url text, title text)"];
    [_db executeUpdate:@"CREATE TABLE TodayList (pic_url text, favorite_num integer, subtitle text, title text)"];
    // 执行查找的操作,调用的方法是executeQuery,参数是sql的查找语句,会返回一个FMResult类型的结果
    FMResultSet *adsResult = [_db executeQuery:@"SELECT * FROM AdsList"];
    FMResultSet *cartoonResult = [_db executeQuery:@"SELECT * FROM CartoonList"];
    FMResultSet *mengestResult = [_db executeQuery:@"SELECT * FROM MengestList"];
    FMResultSet *todayResult = [_db executeQuery:@"SELECT * FROM TodayList"];
    // 类似链表结构
    while ([adsResult next]) {
        NSString *pic_url = [adsResult stringForColumn:@"pic_url"];
        BQAdsModel *model = [[BQAdsModel alloc] init];
        model.pic_url = pic_url;
        [_adsDataArray addObject:model];
    }
   
    while ([cartoonResult next]) {
        NSString *pic_url = [cartoonResult stringForColumn:@"pic_url"];
        BQCartoonModel *model = [[BQCartoonModel alloc] init];
        model.pic_url = pic_url;
        [_cartoonDataArray addObject:model];
    }
    while ([mengestResult next]) {
        NSString *pic_url = [mengestResult stringForColumn:@"pic_url"];
        NSString *title = [mengestResult stringForColumn:@"title"];
        BQMengestModel *model = [[BQMengestModel alloc] init];
        model.pic_url = pic_url;
        model.title = title;
        [_mengestDataArray addObject:model];
    }
    while ([todayResult next]) {
        NSString *pic_url = [todayResult stringForColumn:@"pic_url"];
        NSNumber *favorite_num = [NSNumber numberWithInt:[todayResult intForColumn:@"favorite_num"]];
        NSString *subtitle = [todayResult stringForColumn:@"subtitle"];
        NSString *title = [todayResult stringForColumn:@"title"];
        BQTodayModel *model = [[BQTodayModel alloc] init];
        model.pic_url = pic_url;
        model.favorite_num = favorite_num;
        model.subtitle = subtitle;
        model.title = title;
        [_todayDataArray addObject:model];
    }
}


#pragma mark 点击 跳转 等
// 点击手势
- (void)tapAction:(UITapGestureRecognizer *)tap {
    if ([tap.view isEqual:_newsItem]) {
        _newsItem.imageView.image = [UIImage imageNamed:@"iconfont-new-red"];
        _newsItem.label.textColor = [UIColor redColor];
        _popItem.imageView.image = [UIImage imageNamed:@"iconfont-iconkafei"];
        _popItem.label.textColor = [UIColor lightGrayColor];
        _guessItem.imageView.image = [UIImage imageNamed:@"iconfont-cloud"];
        _guessItem.label.textColor = [UIColor lightGrayColor];
        _itemDataArray = _itemNewDataArray;
        _certificationButton.hidden = YES;
        _collectionView.hidden = NO;
        [_collectionView reloadData];
        if (_itemDataArray.count != 0) {
            _mainScrollView.contentSize = CGSizeMake(kWidth, _titleView.bottom + 64 + 49 + _collectionView.frame.size.height);
        } else {
            _mainScrollView.contentSize = CGSizeMake(kWidth, _titleView.bottom + 64 + 49 + 50);
        }
    } else if ([tap.view isEqual:_popItem]) {
        _newsItem.imageView.image = [UIImage imageNamed:@"iconfont-new"];
        _newsItem.label.textColor = [UIColor lightGrayColor];
        _popItem.imageView.image = [UIImage imageNamed:@"iconfont-iconkafei-red"];
        _popItem.label.textColor = [UIColor redColor];
        _guessItem.imageView.image = [UIImage imageNamed:@"iconfont-cloud"];
        _guessItem.label.textColor = [UIColor lightGrayColor];
        _itemDataArray = _itemPopDataArray;
        _certificationButton.hidden = YES;
        _collectionView.hidden = NO;
        [_collectionView reloadData];
        if (_itemDataArray.count != 0) {
            _mainScrollView.contentSize = CGSizeMake(kWidth, _titleView.bottom + 64 + 49 + _collectionView.frame.size.height);
        } else {
            _mainScrollView.contentSize = CGSizeMake(kWidth, _titleView.bottom + 64 + 49 + 50);
        }
        
    } else {
        _newsItem.imageView.image = [UIImage imageNamed:@"iconfont-new"];
        _newsItem.label.textColor = [UIColor lightGrayColor];
        _popItem.imageView.image = [UIImage imageNamed:@"iconfont-iconkafei"];
        _popItem.label.textColor = [UIColor lightGrayColor];
        _guessItem.imageView.image = [UIImage imageNamed:@"iconfont-cloud-red"];
        _guessItem.label.textColor = [UIColor redColor];
        _certificationButton.hidden = NO;
        _collectionView.hidden = YES;
        _mainScrollView.contentSize = CGSizeMake(kWidth, _titleView.bottom + 49 + 64 + _certificationButton.frame.size.height);
    }
}

// searchButton
- (void)searchButtonAction:(UIButton *)button {
    ZYCategorySearchViewController *searchVC = [[ZYCategorySearchViewController alloc] init];
    searchVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchVC animated:YES];
}

// ads点击跳转

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    
    BQAdsModel *model = _adsDataArray[index];
    if (model.link_url.length >= 42) {
        NSString *postID = [model.link_url substringFromIndex:42];
        ArticleDetailViewController *articalDetailVC = [[ArticleDetailViewController alloc] init];
        articalDetailVC.ID = [NSNumber numberWithInteger:[postID integerValue]];
        // 跳转下一页面时隐藏tabBar
        articalDetailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:articalDetailVC animated:YES];
    }
    
}

// missionCenter跳转
- (void)missionCenterButtonAction:(UIButton *)button {
    BQMissionCenterViewController *missionCenterVC = [[BQMissionCenterViewController alloc] init];
    // 跳转下一页面时隐藏tabBar
    missionCenterVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:missionCenterVC animated:YES];
}

// welfareButtonAction跳转
- (void)welfareButtonAction:(UIButton *)button {
    BQWelfare_BannerViewController *welfareVC = [[BQWelfare_BannerViewController alloc] init];
    welfareVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:welfareVC animated:YES];
}

// TodayView跳转
- (void)todayTapAction:(UITapGestureRecognizer *)todayTap {
    ArticleDetailViewController *articalDetailVC = [[ArticleDetailViewController alloc] init];
    articalDetailVC.ID = ((BQTodayView *)todayTap.view).post_id;
    // 跳转下一页面时隐藏tabBar
    articalDetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:articalDetailVC animated:YES];
}

// 认证
- (void)certificationButtonAction:(UIButton *)button {
    BQHtmlViewController *htmlVC = [[BQHtmlViewController alloc] init];
    htmlVC.myTitle = @"盟主认证";
    htmlVC.urlStr = @"http://m.menghuoapp.com/mzrz/index.html";
    htmlVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:htmlVC animated:YES];
}

// Cartoon点击

- (void)cartoonFirstTap:(UITapGestureRecognizer *)cartoonFirstTap {
    DJSearchViewController *searchViewVC = [[DJSearchViewController alloc] init];
    searchViewVC.name = ((BQCartoonModel *)_cartoonDataArray[0]).title;
    searchViewVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchViewVC animated:YES];
}

- (void)cartoonViewAction:(UIButton *)button {
    DJSearchViewController *searchViewVC = [[DJSearchViewController alloc] init];
    NSInteger index = 0;
    if ([button isEqual:_cartoonView.secondButton]) {
        index = 1;
    } else if ([button isEqual:_cartoonView.thirdButton]) {
        index = 2;
    } else if ([button isEqual:_cartoonView.fourthButton]) {
        index = 3;
    } else {
        index = 4;
    }
    searchViewVC.name = ((BQCartoonModel *)_cartoonDataArray[index]).title;
    searchViewVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchViewVC animated:YES];
}

// Mengest点击
- (void)mengestTap:(UITapGestureRecognizer *)mengestTap {
    DJSearchViewController *searchViewVC = [[DJSearchViewController alloc] init];
    searchViewVC.name = ((UILabel *)[mengestTap.view viewWithTag:200]).text;
    searchViewVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchViewVC animated:YES];
}

// 往期
//- (void)previousButtonAction:(UIButton *)button {
//    TTDiscoverMainViewController *mainVC = [[TTDiscoverMainViewController alloc] init];
//    mainVC.navView.backButton.hidden = NO;
//    [self.navigationController pushViewController:mainVC animated:YES];
//}

// 根据mainScrollView的偏移量的值 判断titleView的精确位置
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    
    if (kHeight == 736) {
        if (_mainScrollView.contentOffset.y >= 1124) {
            _collectionView.scrollEnabled = YES;
            _mainScrollView.contentOffset = CGPointMake(0, 1124);
            if (_collectionView.contentOffset.y < 0) {
                _collectionView.scrollEnabled = NO;
            }
        } else {
            _collectionView.scrollEnabled = NO;
        }
    } else if (kHeight == 667) {
        if (_mainScrollView.contentOffset.y >= 1033) {
            _collectionView.scrollEnabled = YES;
            _mainScrollView.contentOffset = CGPointMake(0, 1033);
            if (_collectionView.contentOffset.y < 0) {
                _collectionView.scrollEnabled = NO;
            }
        } else {
            _collectionView.scrollEnabled = NO;
        }
    } else {
        if (_mainScrollView.contentOffset.y >= 907) {
            _collectionView.scrollEnabled = YES;
            _mainScrollView.contentOffset = CGPointMake(0, 907);
            if (_collectionView.contentOffset.y < 0) {
                _collectionView.scrollEnabled = NO;
            }
        } else {
            _collectionView.scrollEnabled = NO;
        }
    }
}

#pragma mark -- UICollectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _itemDataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZYCategorySecondCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZYCategorySecondCollectionViewCell" forIndexPath:indexPath];
    ZYCategorySecondPageModel *model = _itemDataArray[indexPath.row];
    cell.model = model;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ATMainDetailViewController *mainDetailVC = [[ATMainDetailViewController alloc] init];
    mainDetailVC.item_id = ((ZYCategorySecondPageModel *)_itemDataArray[indexPath.row]).item_id;
    mainDetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:mainDetailVC animated:YES];
}

// 关联pageControl
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if ([scrollView isEqual:_todayScrollView]) {
        NSInteger currentPage = scrollView.contentOffset.x / kWidth;
        _pageControl.currentPage = currentPage;
    }
    
}

#pragma mark 请求数据
- (void)requestData {
    // 创建对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // Ads请求数据
    [manager POST:@"http://api.menghuoapp.com/v1/ads/home" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // responseObject是请求成功下来的数据
        NSArray *dataArray = responseObject[@"data"];
        // 新增前删除旧数据
        [_db executeUpdate:@"DELETE FROM AdsList"];
        // 刷新的时候 有了新数据要把旧数据情况,否则会造成数据重复
        if (_page == 0) {
            [_adsDataArray removeAllObjects];
        }
        for (NSDictionary *dic in dataArray) {
            BQAdsModel *model = [[BQAdsModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_adsDataArray addObject:model];
            // FMDB插入的时候必须是一个对象,如果表里面一个字段是int类型,插入的时候需要插入一个NSNumber对象
            [_db executeUpdate:@"INSERT INTO AdsList (pic_url) VALUES (?)",model.pic_url];
        }
        self.adsScroll();

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
    }];
    // Cartoon请求数据
    [manager POST:@"http://api.menghuoapp.com/v1/tag/cartoon" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // responseObject是请求成功下来的数据
        NSArray *dataArray = responseObject[@"data"];
        [_db executeUpdate:@"DELETE FROM CartoonList"];
        if (_page == 0) {
            [_cartoonDataArray removeAllObjects];
        }
        // 遍历
        for (NSDictionary *dic in dataArray) {
            BQCartoonModel *model = [[BQCartoonModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_cartoonDataArray addObject:model];
            [_db executeUpdate:@"INSERT INTO CartoonList (pic_url) VALUES (?)",model.pic_url];
        }
        [_cartoonView.firstImageView sd_setImageWithURL:[NSURL URLWithString:((BQCartoonModel *)_cartoonDataArray[0]).pic_url]];
        UITapGestureRecognizer *cartoonFirstTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cartoonFirstTap:)];
        _cartoonView.firstImageView.userInteractionEnabled = YES;
        [_cartoonView.firstImageView addGestureRecognizer:cartoonFirstTap];
        
        [_cartoonView.secondButton sd_setImageWithURL:[NSURL URLWithString:((BQCartoonModel *)_cartoonDataArray[1]).pic_url] forState:(UIControlStateNormal)];
        [_cartoonView.secondButton addTarget:self action:@selector(cartoonViewAction:) forControlEvents:(UIControlEventTouchUpInside)];
        
        [_cartoonView.thirdButton sd_setImageWithURL:[NSURL URLWithString:((BQCartoonModel *)_cartoonDataArray[2]).pic_url] forState:(UIControlStateNormal)];
        [_cartoonView.thirdButton addTarget:self action:@selector(cartoonViewAction:) forControlEvents:(UIControlEventTouchUpInside)];
        
        [_cartoonView.fourthButton sd_setImageWithURL:[NSURL URLWithString:((BQCartoonModel *)_cartoonDataArray[3]).pic_url] forState:(UIControlStateNormal)];
        [_cartoonView.fourthButton addTarget:self action:@selector(cartoonViewAction:) forControlEvents:(UIControlEventTouchUpInside)];
        
        [_cartoonView.fifthButton sd_setImageWithURL:[NSURL URLWithString:((BQCartoonModel *)_cartoonDataArray[4]).pic_url] forState:(UIControlStateNormal)];
        [_cartoonView.fifthButton addTarget:self action:@selector(cartoonViewAction:) forControlEvents:(UIControlEventTouchUpInside)];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
    }];
    // Mengest请求数据
    [manager POST:@"http://api.menghuoapp.com/v1/tag/mengest" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // responseObject是请求成功下来的数据
        NSArray *dataArray = responseObject[@"data"];
        [_db executeUpdate:@"DELETE FROM MengestList"];
        if (_page == 0) {
            [_mengestDataArray removeAllObjects];
        }
        // 遍历
        for (NSDictionary *dic in dataArray) {
            BQMengestModel *model = [[BQMengestModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_mengestDataArray addObject:model];
            [_db executeUpdate:@"INSERT INTO MengestList (pic_url, title) VALUES (?, ?)",model.pic_url, model.title];
        }
        // 赋值
        for (int i = 0; i < 10; i++) {
            UIImageView *imageView = [_mengestView.scrollView viewWithTag:i + 100];
            BQMengestModel *model = _mengestDataArray[i];
            [imageView sd_setImageWithURL:[NSURL URLWithString:model.pic_url]];
            UILabel *label = [imageView viewWithTag:200];
            label.text = model.title;
            UITapGestureRecognizer *mengestTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(mengestTap:)];
            imageView.userInteractionEnabled = YES;
            [imageView addGestureRecognizer:mengestTap];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    // Today请求数据
    [manager POST:@"http://api.menghuoapp.com/v1/post/today" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // responseObject是请求成功下来的数据
        NSArray *dataArray = responseObject[@"data"];
        [_db executeUpdate:@"DELETE FROM TodayList"];
        if (_page == 0) {
            [_todayDataArray removeAllObjects];
        }
        // 遍历
        for (NSDictionary *dic in dataArray) {
            BQTodayModel *model = [[BQTodayModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_todayDataArray addObject:model];
            [_db executeUpdate:@"INSERT INTO TodayList (pic_url, favorite_num, subtitle, title) VALUES(?, ?, ?, ?)",model.pic_url, model.favorite_num, model.subtitle, model.title];
        }
        // 赋值
        for (int i = 0; i < 10; i++) {
            BQTodayView *todayView = [_todayScrollView viewWithTag:200 + i];
            BQTodayModel *model = _todayDataArray[i];
            [todayView.imageView sd_setImageWithURL:[NSURL URLWithString:model.pic_url]];
            todayView.title.text = model.title;
            todayView.subtitle.text = model.subtitle;
            todayView.likeLabel.text = [NSString stringWithFormat:@"%@",model.favorite_num];
            todayView.post_id = model.post_id;
            UITapGestureRecognizer *todayTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(todayTapAction:)];
            [todayView addGestureRecognizer:todayTap];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    [self requestItemData];
    // 结束刷新
    [_mainScrollView.mj_header endRefreshing];
    [_collectionView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)requestItemData {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // Item请求数据
    NSMutableDictionary *requestDic = [NSMutableDictionary dictionary];
    requestDic[@"page"] = [NSString stringWithFormat:@"%ld",(long)_page];
    requestDic[@"page_size"] = @"20";
    // new
    [manager POST:@"http://api.menghuoapp.com/v1/item/new" parameters:requestDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *dataArray = responseObject[@"data"];
        if (_page == 0) {
            [_itemNewDataArray removeAllObjects];
        }
        for (NSDictionary *dic in dataArray) {
            ZYCategorySecondPageModel *model = [[ZYCategorySecondPageModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_itemNewDataArray addObject:model];
        }
        if (_itemNewDataArray.count != 0) {
            _mainScrollView.contentSize = CGSizeMake(kWidth, _titleView.bottom + 64 + 49 + _collectionView.frame.size.height);
        }
        [_collectionView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    // pop
    [manager POST:@"http://api.menghuoapp.com/v1/item/pop" parameters:requestDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *dataArray = responseObject[@"data"];
        if (_page == 0) {
            [_itemPopDataArray removeAllObjects];
        }
        for (NSDictionary *dic in dataArray) {
            ZYCategorySecondPageModel *model = [[ZYCategorySecondPageModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_itemPopDataArray addObject:model];
        }
        [_collectionView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    [_collectionView.mj_footer endRefreshing];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
